﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Business;
using Model;
using System.Web.Security;
using MB.Util;
using System.Data.OleDb;
using System.Data;
using System.Transactions;
using System.IO;
using System.Text;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

namespace MvcAppWeb.Controllers
{
    public class GoodsMoveController : BaseDataController
    {
        //
        // GET: /GoodsMove/

        public ActionResult GoodsMove()//主表
        {
            if (Session["UserInfo"] == null) return RedirectToAction("LogOn", "Account");
            else
            {
                AppUserList model = (AppUserList)Session["UserInfo"];
                return View(model);
            }
        }

        public ActionResult GoodsMoveItem()
        {
            if (Session["UserInfo"] == null) return RedirectToAction("LogOn", "Account");
            else
            {
                AppUserList model = (AppUserList)Session["UserInfo"];
                return View(model);
            }
        }
        public JsonResult QueryMain(string GoodsMoveID, string CheckTimeS, string CheckTimeE, string SGoodsCode, string SGoodsName)
        {
            int page = int.Parse(Request["page"].ToString());
            int rows = int.Parse(Request["rows"].ToString());
            int total = 0;
            string where = " where 1=1 ";


            if (!string.IsNullOrEmpty(GoodsMoveID))
            {
                where += " and g.GOODSMOVEID='" + GoodsMoveID + "'";
            }
            if (!string.IsNullOrEmpty(CheckTimeS))
            {
                where += " and g.MOVEDATE>= to_date('" + CheckTimeS + "','yyyy-mm-dd hh24:mi:ss')";
            }
            if (!string.IsNullOrEmpty(CheckTimeE))
            {
                where += " and g.MOVEDATE<= to_date('" + CheckTimeE + "','yyyy-mm-dd hh24:mi:ss')";
            }
            if (!string.IsNullOrEmpty(SGoodsCode))
            {
                where += @" and g.GOODSMOVEID in(select distinct t1.goodsmoveid from lmgoodsmoveitem t1 inner join goods t2 on t1.goodsid=t2.goodsid
                            where t2.goodscode like '%" + SGoodsCode + "%')";
            }
            if (!string.IsNullOrEmpty(SGoodsName))
            {
                where += @" and g.GOODSMOVEID in(select distinct t1.goodsmoveid from lmgoodsmoveitem t1 inner join goods t2 on t1.goodsid=t2.goodsid
                            where t2.goodsname like '%" + SGoodsName + "%')";
            }
            where += @" order by g.GOODSMOVEID ";
            BGoodsMove ogc = new BGoodsMove();
            var result = ogc.GetGoodsMoveList(page, rows, out total, where);

            Dictionary<string, object> json = new Dictionary<string, object>();
            json.Add("total", total);
            json.Add("rows", result);
            return Json(json, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult QueryDetailData(string GoodsMoveID)
        {

            BGoodsMove ogc = new BGoodsMove();
            var result = ogc.GetGoodsMoveItemByGoodsMoveID(GoodsMoveID);

            Dictionary<string, object> json = new Dictionary<string, object>();
            //json.Add("total", total);
            json.Add("rows", result);
            return Json(json, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public string Delete(string ids)
        {
            string sjson = string.Empty;
            try
            {
                BGoodsMove nbl = new BGoodsMove();
                foreach (var id in ids.Split(','))
                {
                    nbl.DeleteGoodsMoveItemByGoodsMoveID(id);
                    nbl.DeleteGoodsMove(id);
                }
                sjson = "{success:true}";
            }
            catch (Exception ex)
            {
                sjson = "{success:false,msg:'" + ex.Message + "'}";
            }
            return sjson;

        }

        [HttpPost]
        public string Saves(string GOODSMOVEID)
        {
            string sjson = string.Empty;
            try
            {
                AppUserList model = (AppUserList)Session["UserInfo"];
                string MoveType = Request["MoveType"];
                string MoveDate = Request["MoveDate"];
                int wid = int.Parse(Request["WAREHOUSEID"]);
                string CellNo = Request["CellNo"];
                string Flag = Request["Flag"];
                string Remark = Request["txtRemark"];
                GoodsMove goodsmove = new GoodsMove();
                goodsmove.MOVETYPE = MoveType;
                DateTime dt = DateTime.Now;
                if (DateTime.TryParse(MoveDate, out dt))
                    goodsmove.MOVEDATE = dt;
                goodsmove.WAREHOUSEID = wid;
                goodsmove.CELLNO = CellNo;
                goodsmove.FLAG = Flag;
                goodsmove.REMARK = Remark;
                goodsmove.CREATOR = model.USERNAME;
                goodsmove.CREATEDATE = DateTime.Now;
                goodsmove.EDITOR = model.USERNAME;
                goodsmove.EDITDATE = DateTime.Now;

                BGoodsMove nbg = new BGoodsMove();
                if (string.IsNullOrEmpty(GOODSMOVEID))
                {
                    nbg.AddGoodsMove(goodsmove);
                }
                else
                {
                    goodsmove.GOODSMOVEID = GOODSMOVEID;
                    nbg.EditGoodsMoveByID(goodsmove);
                }
                sjson = "{success:true}";
            }
            catch (Exception ex)
            {
                sjson = "{success:false,msg:'" + ex.Message + "'}";
            }
            return sjson;
        }


        public JsonResult QueryGoodsMoveItem(string GoodsMoveID)
        {
            int page = int.Parse(Request["page"].ToString());
            int rows = int.Parse(Request["rows"].ToString());
            int total = 0;
            string where = " where 1=1 ";


            if (!string.IsNullOrEmpty(GoodsMoveID))
            {
                where += " and lg.GOODSMOVEID = '" + GoodsMoveID + "'";
            }
            BGoodsMove nbg = new BGoodsMove();
            var result = nbg.GetGoodsMoveItemList(page, rows, out total, where);

            Dictionary<string, object> json = new Dictionary<string, object>();
            json.Add("total", total);
            json.Add("rows", result);
            return Json(json, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public string DeleteItem(string ids)
        {
            string sjson = string.Empty;
            try
            {
                BGoodsMove nbl = new BGoodsMove();
                foreach (var id in ids.Split(','))
                {
                    nbl.DeleteGoodsMoveItem(id);
                }
                sjson = "{success:true}";
            }
            catch (Exception ex)
            {
                sjson = "{success:false,msg:'" + ex.Message + "'}";
            }
            return sjson;

        }

        [HttpPost]
        public string SaveItems(string SEQNO, string GoodsMoveID)
        {
            string sjson = string.Empty;
            try
            {
                string GoodsBatchCode = Request["txtGoodsBatchCode"];
                string FromLocationCode = Request["txtFromLocationCode"];
                string ToLocationCode = Request["txtToLocationCode"];
                string GoodsCode = Request["txtGoodsCode"];
                string QTY = Request["txtQty"];
                string OffShelvesID = Request["txtOffShelvesID"];
                GoodsMoveItem _GoodsMoveItem = new GoodsMoveItem();
                sjson = CheckGoodsMoveItem(GoodsMoveID, GoodsBatchCode, FromLocationCode, ToLocationCode, GoodsCode,
                    QTY, OffShelvesID, out _GoodsMoveItem);

                if (!string.IsNullOrEmpty(sjson))
                    return sjson;
                BGoodsMove nbg = new BGoodsMove();
                if (string.IsNullOrEmpty(SEQNO))
                {
                    nbg.AddGoodsMoveItem(_GoodsMoveItem);
                }
                else
                {
                    _GoodsMoveItem.SEQNO = int.Parse(SEQNO);
                    nbg.EditGoodsMoveItemByID(_GoodsMoveItem);
                }
                sjson = "{success:true}";
            }
            catch (Exception ex)
            {
                sjson = "{success:false,msg:'" + ex.Message + "'}";
            }
            return sjson;
        }

        public ActionResult Audit(string GoodsMoveID)
        {

            AppUserList model = (AppUserList)Session["UserInfo"];

            BGoodsMove nbg = new BGoodsMove();
            nbg.AuditGoodsMove(GoodsMoveID, model);
            return RedirectToAction("GoodsMove");
        }

        [HttpPost]
        public string ImportGoodsMoveItem(HttpPostedFileBase filebase)
        {
            string sjson = string.Empty;
            HttpPostedFileBase file = Request.Files["files"];
            DataTable table = new DataTable();
            string importStr = string.Empty;
            sjson = ImportFile(file, out table, out importStr);
            if (!string.IsNullOrEmpty(sjson))
                return sjson;

            //引用事务机制，出错时，事物回滚
            using (TransactionScope transaction = new TransactionScope())
            {
                try
                {
                    if (!string.IsNullOrEmpty(importStr))//上传的是TXT
                    {
                        List<string> lstStr = importStr.Split(';').ToList();
                        foreach (string item in lstStr)
                        {
                            if (string.IsNullOrEmpty(item))
                                continue;
                            List<string> lstModelStr = item.Split(',').ToList();
                            if (lstModelStr.Count != 7)
                            {
                                sjson = "{success:false,msg:'TXT文件内容格式不正确！'}";
                                return sjson;
                            }
                            string GoodsMoveID = lstModelStr[0].ToString();
                            string GoodsBatchCode = lstModelStr[1].ToString();
                            string FromLocationCode = lstModelStr[2].ToString();
                            string ToLocationCode = lstModelStr[3].ToString();
                            string GoodsCode = lstModelStr[4].ToString();
                            string QTY = lstModelStr[5].ToString();
                            string OffShelvesID = lstModelStr[6].ToString();
                            GoodsMoveItem _GoodsMoveItem = new GoodsMoveItem();
                            sjson = CheckGoodsMoveItem(GoodsMoveID, GoodsBatchCode, FromLocationCode, ToLocationCode, GoodsCode,
                                QTY, OffShelvesID, out _GoodsMoveItem);

                            if (!string.IsNullOrEmpty(sjson))
                                return sjson;
                            BGoodsMove nbg = new BGoodsMove();
                            nbg.AddGoodsMoveItem(_GoodsMoveItem);
                        }
                    }
                    else
                    {
                        for (int i = 0; i < table.Rows.Count; i++)
                        {
                            string GoodsMoveID = table.Rows[i][0].ToString();
                            string GoodsBatchCode = table.Rows[i][1].ToString();
                            string FromLocationCode = table.Rows[i][2].ToString();
                            string ToLocationCode = table.Rows[i][3].ToString();
                            string GoodsCode = table.Rows[i][4].ToString();
                            string QTY = table.Rows[i][6].ToString();
                            string OffShelvesID = table.Rows[i][7].ToString();
                            GoodsMoveItem _GoodsMoveItem = new GoodsMoveItem();
                            sjson = CheckGoodsMoveItem(GoodsMoveID, GoodsBatchCode, FromLocationCode, ToLocationCode, GoodsCode,
                                QTY, OffShelvesID, out _GoodsMoveItem);

                            if (!string.IsNullOrEmpty(sjson))
                                return sjson;

                            BGoodsMove nbg = new BGoodsMove();
                            nbg.AddGoodsMoveItem(_GoodsMoveItem);
                        }
                    }
                    transaction.Complete();
                }
                catch (Exception ex)
                {
                    sjson = "{success:false,msg:'" + ex.Message + "'}";
                    return sjson;
                }
            }
            sjson = "{success:true}";
            System.Threading.Thread.Sleep(2000);
            return sjson;
        }

        [HttpPost]
        public FileResult ExportExcel(int page, int rows, string GoodsMoveID)//导出execl
        {
            //创建Excel文件的对象
            HSSFWorkbook book = new HSSFWorkbook();
            //添加一个sheet
            ISheet sheet1 = book.CreateSheet("Sheet1");
            #region 获取list数据
            int total = 0;
            string where = " where 1=1";
            if (!string.IsNullOrEmpty(GoodsMoveID))
            {
                where += " and lg.GOODSMOVEID = '" + GoodsMoveID + "'";
            }
            BGoodsMove nbg = new BGoodsMove();
            var list = nbg.GetGoodsMoveItemList(page, int.MaxValue, out total, where);
            #endregion
            //给sheet1添加第一行的头部标题
            IRow row1 = sheet1.CreateRow(0);
            List<string> lstTitle = new List<string> { "商品货位搬移单号", "商品批次号", "来源货位", "目的货位", "商品编码", "商品名称", "数量", "下架指令ID" };
            for (int i = 0; i < lstTitle.Count; i++)
            {
                row1.CreateCell(i).SetCellValue(lstTitle[i]);
            }
            //将数据逐步写入sheet1各个行
            for (int i = 0; i < list.Count; i++)
            {
                IRow rowtemp = sheet1.CreateRow(i + 1);
                rowtemp.CreateCell(0).SetCellValue(list[i].GOODSMOVEID);
                rowtemp.CreateCell(1).SetCellValue(list[i].GOODSBATCHCODE);
                rowtemp.CreateCell(2).SetCellValue(list[i].FROMLOCATIONCODE);
                rowtemp.CreateCell(3).SetCellValue(list[i].TOLOCATIONCODE);
                rowtemp.CreateCell(4).SetCellValue(list[i].GOODSCODE);
                rowtemp.CreateCell(5).SetCellValue(list[i].GOODSNAME);
                rowtemp.CreateCell(6).SetCellValue(list[i].QTY.ToString());
                rowtemp.CreateCell(7).SetCellValue(list[i].OFFSHELVESID == null ? string.Empty : list[i].OFFSHELVESID.ToString());
            }
            // 写入到客户端 
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);
            return File(ms, "application/vnd.ms-excel", NewTimeStamp("GoodsMoveItem"));
        }

        private string CheckGoodsMoveItem(string GoodsMoveID, string GoodsBatchCode, string FromLocationCode, string ToLocationCode,
            string GoodsCode, string QTY, string OffShelvesID, out GoodsMoveItem _GoodsMoveItem)
        {
            string sjson = string.Empty;
            AppUserList model = (AppUserList)Session["UserInfo"];
            _GoodsMoveItem = new GoodsMoveItem();
            _GoodsMoveItem.GOODSMOVEID = GoodsMoveID;
            _GoodsMoveItem.GOODSBATCHCODE = GoodsBatchCode;
            #region 校验
            decimal TQTY = 0;
            if (decimal.TryParse(QTY, out TQTY))
                _GoodsMoveItem.QTY = TQTY;
            int n = 0;
            if (int.TryParse(OffShelvesID, out n))
                _GoodsMoveItem.OFFSHELVESID = n;
            BLocation nbl = new BLocation();
            Location checklocation = nbl.CheckLocation(FromLocationCode);
            if (checklocation != null)
            {
                _GoodsMoveItem.FROMLOCATIONID = checklocation.LOCATIONID;
            }
            else
            {
                sjson = "{success:false,msg:'来源货位不存在！'}";
                return sjson;
            }
            checklocation = nbl.CheckLocation(ToLocationCode);
            if (checklocation != null)
            {
                _GoodsMoveItem.TOLOCATIONID = checklocation.LOCATIONID;
            }
            else
            {
                sjson = "{success:false,msg:'目的货位不存在！'}";
                return sjson;
            }
            Goods checkgoods = nbl.CheckGoods(GoodsCode);
            if (checkgoods != null)
            {
                _GoodsMoveItem.GOODSID = checkgoods.GOODSID;
            }
            else
            {
                sjson = "{success:false,msg:'商品编码不存在！'}";
                return sjson;
            }
            #endregion
            return sjson;
        }
    }
}
